package cn.kgc.gmall.utils;

import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 分词器工具类
 *   使用reader的方式进行读取到数据进行分词
 */
public class KeywordUtil {
    /**
     * 传递参数word 将分好的词放入数组中
     * @param word
     * @return
     */
    public static List<String> analyze(String word) {
        List<String> keywordList = new ArrayList<>();
        // 将字符串转化为reader对象
        StringReader reader = new StringReader(word);
        // 使用IK分词器对象
        IKSegmenter ikSegmenter = new IKSegmenter(reader,true);
        Lexeme lexeme = null;

        while (true){
            try {
                if ((lexeme = ikSegmenter.next()) != null){
                    // 从元对象中拿到每个分好的词
                    String lexemeText = lexeme.getLexemeText();
                    // 存入到列表中
                    keywordList.add(lexemeText);
                }else{
                    break;
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }

        return keywordList;

    }

    public static void main(String[] args) throws IOException {
        List<String> word = analyze("小米盒子");
        for (String s : word) {
            System.out.println(s);
        }
    }
}
